import express from "express";
import { body, param } from "express-validator";
import userController from "../controller/user.controller.js";
import tokenHandler from "../middleware/token.middleware.js";
import validateHandler from "../middleware/validate.middleware.js";
const router = express.Router();

// 注册用户
router.post(
  "/register",
  [
    body("username").isLength({ min: 3 }).withMessage("用户名至少3个字符"),
    body("password").isLength({ min: 6 }).withMessage("密码至少6个字符"),
  ],
  validateHandler,
  userController.register,
);

// 登录用户
router.post(
  "/login",
  [
    body("username").isLength({ min: 3 }).withMessage("用户名至少3个字符"),
    body("password").isLength({ min: 6 }).withMessage("密码至少6个字符"),
  ],
  validateHandler,
  userController.login,
);

//获取用户信息 刷新token
router.get("/", tokenHandler, userController.getUserInfo);

//上传头像
router.post("/avatar", tokenHandler, userController.uploadAvatar);

//获取头像
router.get(
  "/avatar/:id",
  [
    param("id")
      .matches(/^[A-Za-z0-9]{6}$/)
      .withMessage("用户ID必须是6位字母或数字组合"),
  ],
  validateHandler,
  userController.getAvatar,
);

//修改用户信息
router.patch(
  "/",
  tokenHandler,
  [body("username").isLength({ min: 3 }).withMessage("用户名至少3个字符")],
  validateHandler,
  userController.updateUser,
);

//修改密码
router.patch(
  "/password",
  tokenHandler,
  [
    body("oldpassword").isLength({ min: 6 }).withMessage("密码至少6个字符"),
    body("newpassword").isLength({ min: 6 }).withMessage("密码至少6个字符"),
  ],
  validateHandler,
  userController.updatePassword,
);

export default router;
